<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="分类" prop="cate_id">
         <treeselect v-model="queryParams.cate_id" :options="cateOptions" style="width:180px"
          :normalizer="normalizer" placeholder="请选择资产分类" />
      </el-form-item>
      <el-form-item label="资产编号" prop="num">
        <el-input
          v-model="queryParams.num"
          placeholder="请输入资产"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="归属部门" prop="dept_id">
        <treeselect v-model="queryParams.dept_id" :options="deptOptions" :normalizer="normalizer" 
          placeholder="请选择归属部门" style="width:180px" />
      </el-form-item>
      <el-form-item label="出售时间" prop="sale_time">
       <el-date-picker
          v-model="queryParams.sale_time"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['asset:sale:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['asset:sale:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="info"
            plain
            icon="el-icon-upload2"
            size="mini"
            @click="handleImport"
              v-hasPermi="['asset:sale:import']"
        >导入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['asset:sale:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="saleList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="分类" align="center" prop="cate_name" />
      <el-table-column label="资产" align="center" prop="asset_num" />
      <el-table-column label="部门名称" align="center" prop="dept_name" />
      <el-table-column label="价格" align="center" prop="price" />
      <el-table-column label="出售原由" align="center" prop="reason" />
      <el-table-column label="出售时间" align="center" prop="sale_time" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.sale_time, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="已出库" align="center" prop="is_out">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_yes_no" :value="scope.row.is_out"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['asset:sale:edit']"
          >修改</el-button>
          <el-button v-if="scope.row.is_out == 'N'"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['asset:sale:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="pager.page"
      :limit.sync="pager.limit"
      @pagination="getList"
    />
    <!-- 添加或修改资产出售对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="资产编号" prop="asset_id">
          <el-select v-model="form.asset_id"  filterable placeholder="请输入资产编号" @change="getAssetInfo"
            remote reserve-keyword :remote-method="searchAsset" :loading="loading">
            <el-option
              v-for="v in assetOptions"
              :key="v.id"
              :label="v.cate_name + ' ' + v.num"
              :value="v.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="资产分类" prop="cate_name">
          <el-input v-model="form.cate_name" placeholder="请输入资产编号" readonly/>
        </el-form-item>
        <el-form-item label="归属部门" prop="dept_name">
          <el-input v-model="form.dept_name" placeholder="请输入归属部门" />
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input v-model="form.price" placeholder="请输入价格" />
        </el-form-item>
        <el-form-item label="出售原由" prop="reason">
          <el-input v-model="form.reason" placeholder="请输入出售原由" />
        </el-form-item>
        <el-form-item label="出售时间" prop="sale_time">
          <el-date-picker clearable
            v-model="form.sale_time"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择出售时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="已出库" prop="is_out">
          <el-radio-group v-model="form.is_out">
            <el-radio
              v-for="dict in dict.type.sys_yes_no"
              :key="dict.value"
              :label="dict.value"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <import-dialog :open="upload" model="asset_sale" @cancel="importCancel" @success="importSuccess" />
  </div>
</template>

<script>
import { apiGet, apiPost, apiPut, apiPatch, apiDelete, apiDs, apiExport, apiDownload } from "@/api/openapi";
import ImportDialog from "@/components/ImportDialog";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "Sale",
  components: {
    ImportDialog, Treeselect
  },
  dicts: ['sys_yes_no'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 资产出售表格数据
      saleList: [],
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        cate_id: null,
        asset_id: null,
        dept_id: null,
        dept_name: null,
        user_id: null,
        user_name: null,
        asset_num: null,
        reason: null,
        sale_time: [],
        is_out: null,
        "@alias": "t",
        "@exp": {
          sale_time: 'bt',
          asset_num: 'lk'
        }
      },
      pager: {
        page: 1,
        limit: 10,
        order: "t.id desc",
      },
      // 导入参数
      upload: false,
      // 表单参数
      form: {},
      assetOptions: [],
      cateOptions: [],
      deptOptions: [],
      userOptions: [],
      // 表单校验
      rules: {
        cate_id: [
          { required: true, message: "分类不能为空", trigger: "blur" }
        ],
        asset_id: [
          { required: true, message: "资产不能为空", trigger: "blur" }
        ],
        dept_id: [
          { required: true, message: "归属部门不能为空", trigger: "blur" }
        ],
        dept_name: [
          { required: true, message: "部门名称不能为空", trigger: "blur" }
        ],
        user_id: [
          { required: true, message: "操作人不能为空", trigger: "blur" }
        ],
        user_name: [
          { required: true, message: "操作人姓名不能为空", trigger: "blur" }
        ],
        price: [
          { required: true, message: "价格不能为空", trigger: "blur" }
        ],
        reason: [
          { required: true, message: "出售原由不能为空", trigger: "blur" }
        ],
        sale_time: [
          { required: true, message: "出售时间不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
    apiDs('asset_category_select').then(response=>{
        this.cateOptions = this.handleTree(response.data, "value", "pid");
    });
    apiDs('dept_select').then(response=>{
        this.deptOptions = this.handleTree(response.data, "value", "parent_id");
    });
    apiDs('user_select').then(response=>{
        this.userOptions = response.data;
    });
  },
  methods: {
    /** 查询资产出售列表 */
    getList() {
      this.loading = true;
      let params = {};
      params['asset_sale'] = {...this.queryParams};
      if(this.queryParams.sale_time.length == 0){
        params['asset_sale']['sale_time'] = null;
      }
      params['asset_category'] = {
          "@alias": "c",
          "@join": "c.id = t.cate_id",
          "@column":"name cate_name"
      };
      params['@pager'] = this.pager;
      apiGet(params).then(response => {
        this.saleList = response.data.rows;
        this.total = response.data.total;
        this.loading = false;
      });
    },
    /** 转换资产分类数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.value,
        label: node.label,
        children: node.children
      };
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        cate_id: null,
        asset_id: null,
        asset_num: null,
        dept_id: null,
        dept_name: null,
        user_id: "@userId()",
        user_name: "@userName()",
        price: null,
        reason: null,
        sale_time: null,
        is_out: 'N'
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.pager.page = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    searchAsset(query) {
      if (query === '') {
        this.assetOptions = [];
        return;
      }

      this.loading = true;
      let data = {"@pager":{limit:1000}};
      data['asset_info'] = {
        "@alias": "t",
        "@column":"*",
        "num": query,
        "status":"6",
        "@exp":{num:'lk', status:"neq"}
      };
      data['asset_category'] = {
          "@alias": "c",
          "@join": "c.id = t.cate_id",
          "@column":"name cate_name"
      };
      data['sys_dept'] = {
          "@alias": "d",
          "@join": "d.dept_id = t.dept_id",
          "@column":"dept_name"
      };
      apiGet(data).then(response => {
        this.assetOptions = response.data.rows;
        this.loading = false;
      });
    },
    getAssetInfo() {
      for(var i=0;i<this.assetOptions.length;i++){
        if(this.assetOptions[i].id == this.form.asset_id){
          this.form.asset_num = this.assetOptions[i].num;
          this.form.cate_id = this.assetOptions[i].cate_id;
          this.form.cate_name = this.assetOptions[i].cate_name;
          this.form.house_id = this.assetOptions[i].house_id;
          this.form.dept_id = this.assetOptions[i].dept_id;
          this.form.dept_name = this.assetOptions[i].dept_name;
          this.form.price = this.assetOptions[i].price;
        }
      }
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加资产出售";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
        let data = {};
        data['asset_sale'] = { id:id};
      apiGet(data).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改资产出售";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
            let data = {};
            data['asset_sale'] = this.form;
            data['@tags'] = ['asset_sale'];
          if (this.form.id != null) {
            apiPut(data).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            data['asset_info'] = {
              id:this.form.asset_id,
              price:this.form.price,
              status:6
            };
            data['@tags'].push('asset_info');
            apiPatch(data).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除选中的资产出售数据？').then(function() {
        let data = {};
        data['asset_sale'] = { id:ids, "@exp":{id:"in"}};
        data['@tags'] = ['asset_sale'];
        return apiDelete(data);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload = true;
    },
    importSuccess(msg) {
        this.upload = false;
        this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
        this.getList();
    },
    importCancel() {
        this.upload = false;
    },
    /** 导出按钮操作 */
    handleExport() {
        let params = {};
      params['asset_sale'] = {...this.queryParams};
      if(this.queryParams.sale_time.length == 0){
        params['asset_sale']['sale_time'] = null;
      }
      params['@pager'] = {page:1, limit:10000};
      apiExport(params).then(response => {
        apiDownload(response.msg);
      });
    }
  }
};
</script>
